<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="increment">+1</button>
    <span id="box">0</span>
    <button id="decrement">-1</button>
    <script src="./myRedux.js"></script>
    <script src="middlewares/logger.js"></script>
    <script src="middlewares/thunk.js"></script>
    <script>
        function counterReducer(state, action) {
            switch (action.type) {
                case "increment":
                    return state + 1;
                case "decrement":
                    return state - 1;
                default:
                    return state;
            }
        }

        function enhancer(createStore) {
            return function (reducer, preloadedState) {
                var store = createStore(reducer, preloadedState)
                var dispatch = store.dispatch
                //重新定义dispatch
                function _dispatch(action) {
                    //如果是函数 使用函数调用dispatch
                    if (typeof action === 'function') {
                        return action(dispatch)
                    }
                    dispatch(action);
                }
                return {
                    ...store,
                    dispatch: _dispatch
                }
            }
        }
        //把一个由多个不同 reducer 函数作为 value 的 object，合并成一个最终的 reducer 函数，然后就可以对这个 reducer 调用 createStore。
        var rootReducer = combineReducers({ counter: counterReducer })

        var store = createStore(rootReducer, { counter: 100 }, applyMiddleware(logger, thunk));

        store.subscribe(function () {
            //获取最新状态
            document.getElementById('box').innerHTML = store.getState().counter
        })
        //bindActionCreators是redux的一个自带函数，作用是将单个或多个ActionCreator转化为dispatch(action)的函数集合形式。
        var actions = bindActionCreators({ increment, decrement }, store.dispatch);

        function increment() {
            return { type: "increment" }
        }

        function decrement() {
            return { type: "decrement" };
        }

        //获取加 按钮
        document.getElementById("increment").onclick = function () {
            // logger -> thunk -> reducer
            //触发 action 让数值加1
            // store.dispatch({ type: "increment" });
            actions.increment()
            // store.dispatch(function(dispatch){
            //     setTimeout(() => {
            //         dispatch({ type: "increment" })
            //     }, 1000);
            // });
        };

        //获取减  按钮
        document.getElementById("decrement").onclick = function () {
            // store.dispatch({ type: "decrement" });
            actions.decrement()
        };

    </script>
</body>

</html>